<?php
namespace App\Http\Controllers\Admin;

use App\Model\CorpMaster;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use App\Model\StaffModel;
use SplFileObject;
use App\Model\UserModel;

class CorpController extends Controller
{

    public function addCorpMaster(Request $request)
    {
        $corpMaster = new CorpMaster();
        $corpInfo = $request->input('CorpMaster');
        $corp_id = $corpInfo['corp_id'];
        $usernfo = $request->input('userMaster');
        // $corpMaster->updUserPass($usernfo['user_id'], $usernfo['password']);
        $login_id = cookie::get('login_id');
        $user_id = cookie::get('user_id');
        $password = $usernfo['password'];
        $userInfo = array(
            $login_id,
            $user_id,
            $password
        );
        $allInfo = [
            null,
            $userInfo
        ];
        // $corpMaster->updUserPass($password, $user_id);

        if (empty($corp_id)) {

            $corpInfo['created_at'] = now();
            $corpInfo['updated_at'] = now();
            $corpInfo['delete_flg'] = 0;

            $corp_id = $corpMaster->addCorpMaster($corpInfo);
            $corpInfo = $corpMaster->getCorpInfoByCorpId($corp_id);

            $userMaster = new UserModel();
            $newLoginId = $userMaster->genNewUser();
            $newUserInfo = array();
            $newUserInfo['auth'] = Config::get('const.authAdmin');
            $newUserInfo['corp_id'] = $corp_id;
            $newUserInfo['created_at'] = now();
            $newUserInfo['updated_at'] = now();
            $newUserInfo['delete_flg'] = 0;
            $newUserInfo['login_id'] = $newLoginId;
            $newUserInfo['user_name'] = $newLoginId;
            $newUserInfo['password'] = $newLoginId;
            // var_dump($userInfo);exit;
            $flag = $userMaster->addUser($newUserInfo);

            if (! empty($corp_id)) {
                $allInfo = [
                    $corpInfo[0],
                    $userInfo
                ];
                return redirect('/admin/corp')->with('success', '会社を登録しました。');
            } else {
                return view('admin.corp', array(
                    'allInfo' => $allInfo
                ))->with('error', '新規失败！');
            }
        } else {
            $list = 'corp_id';
            $data = $corp_id;
            $corpInfo['updated_at'] = now();
            $corpMaster->updCorpMaster($data, $list, $corpInfo);
        }
        return redirect('/admin/corp')->with('success', '削除成功！');
    }

    public function delCorpMaster(Request $request)
    {
        $corpMasterInfo = $request->input('CorpMaster');
        $corp_id = $corpMasterInfo['corp_id'];

        $corpMaster = new CorpMaster();
        $flag = $corpMaster->delCorpMaster($corp_id);
        $login_id = cookie::get('login_id');
        $user_id = cookie::get('user_id');
        $password = cookie::get('password');
        $userInfo = array(
            $login_id,
            $user_id,
            $password
        );
        $allInfo = [
            null,
            $userInfo
        ];
        return redirect('/admin/corp')->with('success', '削除成功！');
    }

    public function delcorpInfo(Request $request)
    {
        $corp_id = $request->input('corp_id');

        $corpMaster = new CorpMaster();
        $flag = $corpMaster->delCorpMaster($corp_id);

        if ($flag) {
            return redirect('/admin/corp')->with('success', '削除成功！');
        } else {
            return redirect('/admin/corp')->with('error', '削除失败！');
        }
    }

    public function deleteStaff(Request $request)
    {
        $staff_id = $request->input('staff_id');
        $data = array(
            "staff_id" => $staff_id,
            "delete_flg" => 1
        );
        $staffMaster = new StaffModel();
        $staffMaster->delstaff($staff_id, "staff_id", $data);
        return "Success";
    }

    /**
     * 担当者保存
     *
     * @param Request $request
     * @return string
     */
    public function saveStaff(Request $request)
    {
        $staff_id = $request->input('staff_id');
        $staff_name = $request->input('staff_name');
        $staff_kana = $request->input('staff_kana');
        $staff_mail = $request->input('staff_mail');
        $staff_tel = $request->input('staff_tel');
        $send_bill_mail = $request->input('send_bill_mail');
        $send_sale_mail = $request->input('send_sale_mail');
        $send_transfer_mail = $request->input('send_transfer_mail');
        $corp_id = $request->input('corp_id');
        $data = array(
            "staff_id" => $staff_id,
            "staff_name" => $staff_name,
            "staff_kana" => $staff_kana,
            "tel" => $staff_tel,
            "mail" => $staff_mail,
            "send_bill_mail" => $send_bill_mail,
            "send_sale_mail" => $send_sale_mail,
            "send_transfer_mail" => $send_transfer_mail,
            "corp_id" => $corp_id,
            "delete_flg" => 0
        );

        $staffMaster = new StaffModel();
        if ($staff_id != null && $staff_id !== "") {
            // 更新
            $staffMaster->updstaff($staff_id, "staff_id", $data);
        } else {
            // 新規
            $staffMaster->addstaff($data);
        }
        return "Success";
    }

    function queryCorpMaster(Request $request)
    {
        $auth = cookie::get('auth');
        if ($auth == Config::get('const.adrojapan')) {

            $corpMaster = new CorpMaster();

            $corpInfo = $corpMaster->getCorpMaster();
            return view('admin.corplist', array(
                'corpInfos' => $corpInfo
            )); // 返回视图
        } elseif ($auth == Config::get('const.authAdmin')) {
            $corpId = cookie::get('corp_id');
            $login_id = cookie::get('login_id');
            $user_id = cookie::get('user_id');
            $password = cookie::get('password');

            $userInfo = array(
                $login_id,
                $user_id,
                $password
            );

            $corpInfoPara = Null;

            if (! empty($corpId)) {
                $corpMaster = new CorpMaster();
                $corpInfo = $corpMaster->getCorpInfoByCorpId($corpId);
                if (! empty($corpInfo[0])) {
                    $corpInfoPara = $corpInfo[0];
                }
            }
            $allInfo = [
                $corpInfoPara,
                $userInfo
            ];

            return view('admin.corp', array(
                'allInfo' => $allInfo
            )); // 返回视图
        } elseif ($auth == Config::get('const.authCustomer')) {
            return redirect('/admin/corp')->with('messageInfo', '訪問権利はありません！');
        }
    }

    function index(Request $request)
    {
        $corpId = $request->input('corp_id');
        $userInfo = array();
        $userMaster = new UserModel();
        $corpMaster = new CorpMaster();
        $corpInfoPara = null;
        if (! empty($corpId)) {
            $corpInfo = $corpMaster->getCorpInfoByCorpId($corpId);
            $userInfo = $userMaster->readCorpUserMaster($corpId);
            if (! empty($corpInfo[0])) {
                $corpInfoPara = $corpInfo[0];
            }
        } else {
            $corpInfoPara = $corpMaster;
            $userInfo[0] = $userMaster;
        }
        $allInfo = [
            $corpInfoPara,
            $userInfo[0]
        ];
        $staffMaster = new StaffModel();
        $staffInfos = $staffMaster->readCorpStaffMaster($corpId);

        return view('admin.corp', array(
            'allInfo' => $allInfo,
            'staffInfos' => $staffInfos
        )); // 返回视图
    }

    function getPrice($parameters)
    {
        $corpMaster = new CorpMaster();
        $priceGroupInfo = $corpMaster->getDiscMasterByCataId();
        return json_encode($priceGroupInfo);
    }

    function getStaffs(Request $request)
    {
        $corpId = $request->input('corp_id');
        $staffMaster = new StaffModel();
        $staffInfos = $staffMaster->readCorpStaffMaster($corpId);
        return response()->json($staffInfos);
    }

    /*
     * Name CSV取り込み
     *
     */
    public function inputCsvCorpMaster(Request $request)
    {

        // setlocaleを設定
        setlocale(LC_ALL, 'ja_JP.UTF-8');

        // アップロードしたファイルを取得
        $uploaded_file = $request->file('csv_file');
        $filecsv = $_FILES['csv_file'];
        // ファイル空の判断
        // ファイルフォーマットの判断
        $file_type = substr(strstr($filecsv['name'], '.'), 1);
        if ($file_type != 'csv') {
            echo "<script type=\"text/javascript\">alert(\"ファイルフォーマットのエラーです,もう一度アップロードしてください!\");window.history.go(-1);</script>";
            exit();
        }

        // アップロードしたファイルの絶対パスを取得
        $file_path = $request->file('csv_file')->path($uploaded_file);
        $file = new SplFileObject($file_path);
        $file->setFlags(SplFileObject::READ_CSV);

        $row_count = 1;
        $flag = false;
        foreach ($file as $row) {

            if (isset($row[0]) && ! empty($row[0])) {

                // 1行目のヘッダーは取り込まない
                if ($row_count > 1) {
                    if (isset($row[0]) && ! empty($row[0])) {
                        $corp_name = mb_convert_encoding($row[0], 'UTF-8', 'SJIS');
                        var_dump($corp_name);
                    }
                    if (isset($row[1]) && ! empty($row[1])) {
                        $corp_catelogue = mb_convert_encoding($row[1], 'UTF-8', 'SJIS');
                        var_dump($corp_catelogue);
                    }
                    if (isset($row[2]) && ! empty($row[2])) {
                        $corp_postcode = mb_convert_encoding($row[2], 'UTF-8', 'SJIS');
                        var_dump($corp_postcode);
                    }
                    if (isset($row[3]) && ! empty($row[3])) {
                        $corp_adress = mb_convert_encoding($row[3], 'UTF-8', 'SJIS');
                        var_dump($corp_adress);
                    }
                    if (isset($row[4]) && ! empty($row[4])) {
                        $corp_tel = mb_convert_encoding($row[4], 'UTF-8', 'SJIS');
                        var_dump($corp_tel);
                    }
                    if (isset($row[5]) && ! empty($row[5])) {
                        $corp_fax = mb_convert_encoding($row[5], 'UTF-8', 'SJIS');
                        var_dump($corp_fax);
                    }
                    if (isset($row[6]) && ! empty($row[6])) {
                        $corp_mail = mb_convert_encoding($row[6], 'UTF-8', 'SJIS');
                        var_dump($corp_mail);
                    }
                    if (isset($row[7]) && ! empty($row[7])) {
                        $corp_stuff = mb_convert_encoding($row[7], 'UTF-8', 'SJIS');
                        var_dump($corp_stuff);
                    }
                    if (isset($row[8]) && ! empty($row[8])) {
                        $stuff_kana = mb_convert_encoding($row[8], 'UTF-8', 'SJIS');
                        var_dump($stuff_kana);
                    }
                    if (isset($row[9]) && ! empty($row[9])) {
                        $stuff_mail = mb_convert_encoding($row[9], 'UTF-8', 'SJIS');
                        var_dump($stuff_mail);
                    }
                    if (isset($row[10]) && ! empty($row[10])) {
                        $corp_stuff_telephone = mb_convert_encoding($row[10], 'UTF-8', 'SJIS');
                        var_dump($corp_stuff_telephone);
                    }
                    if (isset($row[11]) && ! empty($row[11])) {
                        $corp_stuff_kana = mb_convert_encoding($row[11], 'UTF-8', 'SJIS');
                        var_dump($corp_stuff_kana);
                    }
                    if (isset($row[12]) && ! empty($row[12])) {
                        $corp_stuff_mail = mb_convert_encoding($row[12], 'UTF-8', 'SJIS');
                        var_dump($corp_stuff_mail);
                    }
                    if (isset($row[13]) && ! empty($row[13])) {
                        $price_rate = mb_convert_encoding($row[13], 'UTF-8', 'SJIS');
                        var_dump($price_rate);
                    }
                    if (isset($row[14]) && ! empty($row[14])) {
                        $remark = mb_convert_encoding($row[14], 'UTF-8', 'SJIS');
                        var_dump($remark);
                    }
                    if (isset($row[15]) && ! empty($row[15])) {
                        $delete_flg = mb_convert_encoding($row[15], 'UTF-8', 'SJIS');
                        var_dump($delete_flg);
                    }
                    if (isset($row[16]) && ! empty($row[16])) {
                        $created_at = mb_convert_encoding($row[16], 'UTF-8', 'SJIS');
                        var_dump($created_at);
                    }
                    if (isset($row[17]) && ! empty($row[17])) {
                        $updated_at = mb_convert_encoding($row[17], 'UTF-8', 'SJIS');
                        var_dump($updated_at);
                    }
                    if (isset($row[18]) && ! empty($row[18])) {
                        $buil_name = mb_convert_encoding($row[18], 'UTF-8', 'SJIS');
                        var_dump($buil_name);
                    }
                }
            }
            // ここで値をデータベースに保存したりする
            $corpMaster = new CorpMaster();
            $flag = $corpMaster->addCsvCorpMaster($row);
            $row_count ++;
        }

        if ($flag) {
            return redirect('/admin/corp')->with('success', '添加成功！');
        } else {
            return redirect('/admin/corp')->with('error', '添加失敗！');
        }
    }
}
